<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;

class AnonymousAuthenticate
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        config(['auth.defaults.guard' => 'frontend']);
        try {
            $token = JWTAuth::getToken();
            if (empty($token)) {
                throw new \Exception('User not found');
            }
            if (!$user = JWTAuth::toUser($token)) {
                throw new \Exception('User not found');
            }
        } catch (\Exception $e) {
            auth('frontend')->setUser(new User([
                'id' => -1,
                'name' => 'anonymous',
                'mobile' => 'anonymous',
                'status' => 1
            ]));
        }

        return $next($request);
    }
}
